<template>
  <div class="dialog-container">
    <div class="dialog-content">
      <el-form ref="form" :rules="rules" size="mini" :model="form" label-width="80px">
        <el-form-item prop="name" label="标签名称">
          <el-input maxlength="20" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 0; margin-top: 40px">
          <div class="panel-line flex-end">
            <el-button @click="handleCancel">取消</el-button>
            <el-button @click="handleDelete" type="danger" v-if="editModel === 'edit'">删除</el-button>
            <el-button :loading="loading" type="primary" @click="handleSubmit">保存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { apiLabelSave, apiLabelDel } from '@/api/dataStatistics'

export default {
  name: 'DialogAdd',
  props: {
    editModel: {
      type: String,
      default: 'add',
    },
    info: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      loading: false,
      form: {
        name: '',
      },
      rules: {
        name: [{ required: true, message: '请输入标签名称', trigger: 'change' }],
      },
    }
  },
  mounted() {
    this.init()
  },
  destroyed() {},
  methods: {
    init() {
      if (this.editModel === 'edit' && this.info.id) {
        this.form.id = this.info.id
        this.form.name = this.info.name
      }
    },
    // 取消
    handleCancel() {
      this.$emit('close')
    },
    // 保存
    handleSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          apiLabelSave(this.form)
            .then((res) => {
              this.$message({
                message: '保存成功',
                type: 'success',
              })
              setTimeout(() => {
                this.loading = false
                this.$emit('success')
              }, 1000)
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    },
    // 删除
    handleDelete() {
      this.$confirm('确认要删除这条信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        apiLabelDel({ id: this.form.id }).then((res) => {
          this.$message({
            type: 'success',
            message: '操作成功!',
          })
          setTimeout(() => {
            this.$emit('success')
          }, 1000)
        })
      })
    },
  },
}
</script>

<style scoped lang="scss"></style>
